#!/usr/bin/env node
// depends on package ciecam02
// this is from the readme of the package, the gradient example.
// usage: gradient startcolor endcolor steps
// eg: gradient 333333 bbbbbb 5

var ciebase = require("ciebase")
var ciecam02 = require("ciecam02")

var {rgb, workspace, illuminant} = ciebase,
    {cfs} = ciecam02,
    xyz = ciebase.xyz(workspace.sRGB, illuminant.D65);

var viewingConditions = {
    whitePoint: illuminant.D65,
    adaptingLuminance: 40,
    backgroundLuminance: 20,
    surroundType: "average",
    discounting: false
};

// By default, 7 correlates are returned when converting from XYZ to CAM.
// For the purpose of this example, we will limit ourselves to the JCh correlates.
// (J is the lightness, C the chroma and h the hue.)
var cam = ciecam02.cam(viewingConditions, cfs("JCh")),
    gamut = ciecam02.gamut(xyz, cam),
    {min, max} = Math;

function hexToCam(hex) {
    return cam.fromXyz(xyz.fromRgb(rgb.fromHex(hex)));
}

function crop (v) {
    return max(0, min(1, v));
}

var {lerp} = ciecam02,
    camStart = hexToCam(process.argv[2]),
    camEnd = hexToCam(process.argv[3]);

function gradient (camStart, camEnd, steps=3) {
    var result = [];
    for (var ε = 1/(steps+1), t = 0; steps > -2; t += ε, steps -= 1) {
        let camBetween = lerp(camStart, camEnd, crop(t)),
            hex = rgb.toHex(xyz.toRgb(cam.toXyz(camBetween)).map(crop));
        result.push(hex);
    }
    return result;
}

var result = gradient(camStart, camEnd, parseInt(process.argv[4]));

// only use the steps, not the ends.
result.pop();
result.reverse().pop();
result.reverse();

result.forEach(color => console.log(color));
